import { defineConfig } from 'vitepress';
import { fileURLToPath, URL } from 'node:url';
import Icons from 'unplugin-icons/vite';
import { FileSystemIconLoader } from 'unplugin-icons/loaders';
import { withMermaid } from 'vitepress-plugin-mermaid';
import markdownItTextualUml from '../src/components/markdownItTextualUml';


export default withMermaid(
  defineConfig({
    base: '/docs/',
    title: 'openUBMC',
    description: 'A VitePress Site',
    srcDir: 'docs',
    cleanUrls: false,
    ignoreDeadLinks: true,
    appearance: false, // enable dynamic scripts for dark mode
    titleTemplate: true,
    themeConfig: {},
    head: [
      [
        'link',
        {
          rel: 'icon',
          href: '/docs/favicon.ico',
        },
      ],
    ],
    locales: {
      zh: {
        label: '简体中文',
        lang: 'zh',
        title: '文档中心 | openUBMC',
        description: 'openUBMC',
      },
    },
    markdown: {
      math: true,
      plantuml: true,
      config: (md) => {
        md.use(markdownItTextualUml);
        md.renderer.rules.code_inline = (tokens, idx) => {
          const content = tokens[idx].content;
          // 转义
          const escapedContent = md.utils.escapeHtml(content);
          // 处理双花括号
          return `<code v-pre>${ escapedContent }</code>`;
        };
        md.renderer.rules.image = function(tokens, idx, options, env, self) {
          // 原始图片 HTML
          const imgHtml = self.renderToken(tokens, idx, options);
          return `<ImageWrapper>${ imgHtml }</ImageWrapper>`;
        };
        const defaultRender = md.renderer.rules.fence;

        md.renderer.rules.fence = (tokens, idx, options, env, self) => {
          const token = tokens[idx];
          const info = token.info.trim();
          const language = info.split(' ')[0] || 'text';
          // 生成默认高亮 HTML
          let rawHtml = defaultRender(tokens, idx, options, env, self);

          if (['mermaid', 'plantuml', 'ditaa', 'dot'].includes(language)) {
            return `<ImageWrapper>${ rawHtml }</ImageWrapper>`;
          }
          // 仅处理代码块（跳过非代码块内容）
          const codeContent = token.content;
          // 提取所有以 # 开头的行
          const commentLines = codeContent.split('\n').filter((line) => line.trim().startsWith('#'));
          commentLines.forEach((line) => {
            rawHtml = rawHtml.replace(line, `<span class="comment-line">${ line }</span>`);
          });
          // 包裹到自定义组件中
          return `<CodeBlockWrapper language="${ language }" >${ rawHtml }</CodeBlockWrapper>`;
        };

        // 保存默认的表格渲染函数
        const defaultTableOpen =
          md.renderer.rules.table_open ||
          function(tokens, idx, options, env, self) {
            return self.renderToken(tokens, idx, options);
          };
        const defaultTableClose =
          md.renderer.rules.table_close ||
          function(tokens, idx, options, env, self) {
            return self.renderToken(tokens, idx, options);
          };

        // 重写表格开始标签
        md.renderer.rules.table_open = (tokens, idx, options, env, self) => {
          return '<div class="md-table">' + defaultTableOpen(tokens, idx, options, env, self);
        };

        // 重写表格结束标签
        md.renderer.rules.table_close = (tokens, idx, options, env, self) => {
          return defaultTableClose(tokens, idx, options, env, self) + '</div>';
        };
      },
    },
    vite: {
      build: {
        cssCodeSplit: true,
      },
      plugins: [
        Icons({
          compiler: 'vue3',
          customCollections: {
            app: FileSystemIconLoader(fileURLToPath(new URL('../src/assets/svg-icons', import.meta.url))),
          },
        }),
      ],
      css: {
        preprocessorOptions: {
          scss: {
            api: 'modern-compiler', // or "modern"
            charset: false,
            additionalData: `
          @use "@/assets/style/mixin/screen.scss" as *;
          @use "@/assets/style/mixin/font.scss" as *;
          @use "@/assets/style/mixin/common.scss" as *;
          `,
            silenceDeprecations: ['mixed-decls'],
          },
        },
      },
      publicDir: fileURLToPath(new URL('../docs/public', import.meta.url)),
      optimizeDeps: { include: ['@braintree/sanitize-url', 'mermaid'] },
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('../src', import.meta.url)),
          debug: 'debug/',
        },
      },
      server: {
        port: 5174,
        proxy: {
          '/api-omapi/': {
            target: 'https://usercenter.openubmc.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-omapi/, ''),
          },
          '/api-meeting/': {
            target: 'https://meeting-center.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-meeting/, '/api/'),
          },
          '/api-search/': {
            target: 'https://openubmc-doc-search.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-search/, ''),
          },
          '/api-message/': {
            target: 'https://message-center-openubmc.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-message/, ''),
          },
          '/api-datastat/': {
            target: 'https://datastat-develop.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-datastat/, ''),
          },
          '/api-dsapi/': {
            target: 'https://dsapi.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-dsapi/, ''),
          },
          '/api-collect/': {
            target: 'https://collect.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-collect/, '/api/'),
          },
          '/api-easysoftware/': {
            target: 'https://openubmc-easy.test.osinfra.cn/',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api-easysoftware/, ''),
          },
        },
      },
    },
  }),
);
